

'''
商品详情信息采集

/*PHP是世界上最好的语言*/

'''

import requests, re ,os, time,json
from urllib.parse import quote, urlencode
from manage.helper import Helper
from base_config import *
from decimal import Decimal
from manage.exception import Exceptions


class GoodsCase( object ):

    def __init__(self):

        pass

    # 请求拼多多页面获取加密参数
    def requestParams(self,params):

        keyword = params['keywords']

        r = requests.get( url = domain_url['other']['pdd_params_url'] + quote( keyword ), headers = header )


        if r.status_code == 200 and 'list_id' in r.text:

            text = r.text

            list_id = re.search(r'"listID":"([^"]+)"', text).group(1)

            flip = re.search(r'"flip":"([^"]+)"', text).group(1)

            data =  {
                'list_id':list_id,
                'flip':flip
            }

            require = urlencode( self.requestIndex( data ,params['keywords'],params['page']) )

            r = requests.get( url = domain_url['pinduoduo']['pdd_detail_url'] + require , headers = header )

            if r.status_code == 200:

                return r.json()


            elif r.status_code == 403:

                '''
                任务失败,生成失败任务签名
                '''

                data = {

                    'id':params['taskid']
                }


                sign = Helper.genSign( data )

                data['sign'] = sign
                # data['content'] = '商品详情信息任务'

                '''
                返回任务失败结果
                '''
                Exceptions.failTask( data )

                return False


    # 拼接加密参数
    def requestIndex(self,params,keyword,page):

        data = {

            "source": "search",
            "search_met": "",
            "list_id": params['list_id'],
            "sort": "default",
            "filter": "",
            "q": "{0}".format(keyword),
            "page": "{0}".format(page),
            "size": "50",
            "flip": params['flip'],
            "anti_content": os.popen(f"node anti_content.js").read().strip(),
            "pdduid": ""

        }
        return data


    # 解析商品详情信息
    def parseJson(self,params):

        global track
        #追踪任务id
        #
        track = params

        items = self.requestParams(params)


        if not items:

            print('[商品详情任务采集]: IP被检测 等待程序重新启动:%s'%(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time()))))


            os._exit(0)

        elif len( items['items']) == 0:

            # 采集数量为0 返回成功状态

            data = {
                'id':params['taskid']
            }
            # 生成加密签名
            sign = Helper.genSign( data )

            #返回任务成功
            data['sign'] = sign

            Exceptions.successTask( data )

        else:

            # 定义商品详情列表
            infoList = []

            page = int( params['page'] )

            # 排名参数设置默认0
            num  = 0

            # 提取关键字段
            for item in items['items']:

                # 循环叠加商品排名
                num += 1

                # 计算排名信息

                rank = (page - 1)*20  + num

                data =  {

                    "goodsid": str(item['goods_id']),
                    "goodsname": item['short_name'],
                    "keywords": params['keywords'],
                    "pic": item['thumb_url'],
                    "price": str(Decimal(item['price'] / 100).quantize(Decimal('0.00'))),
                    "rank":'{0}'.format( str(rank) ),
                    "salescount":str(item['sales']),

                }

                print( '[商品排名采集任务]: %s\t关键字采集结果:'%params['keywords'], data['goodsname'] )

                infoList.append( data )


            #websocket上传关键词详情
            Helper.webConn( json.dumps(infoList) )

            print('[商品排名采集任务]: 关键词:%s\t通过websocket上传成功服务器成功' % params['keywords'])


            '''
            任务成功,生成签名
            '''

            data = {

                'id':params['taskid']
            }

            sign = Helper.genSign( data )

            data['sign'] = sign

            Exceptions.successTask( data )

    def  testSign( self,obj ):

        data = {

            "goodsid" : obj['goodsid'],
            "goodsname" : obj['goodsname']

        }
        r = requests.post( url = domain_url['test_sign_url']  , headers=header, data=data)

        if r.status_code == 200:

            print( r.text )

        return None

if __name__ == '__main__':

    g = GoodsCase()

    data = {'taskid': '3', 'sortby': None, 'addby': None, 'createtime': '2019-08-21 09:15:48', 'editby': None, 'edittime': None, 'type': '1', 'keywords': ' 0号 ', 'classcode': None, 'goodsid': None, 'task_start_time': None, 'task_end_time': None, 'status': '0', 'recordscount': None, 'memo': None, 'page': '1', 'processcode': '23E73F39-3B5B-00C4-81F1-8D7B5C2BF563'}

    g.parseJson( data )